package org.wlgzs.office_exam_student.servlet;

import org.wlgzs.office_exam_student.service.office.OfficeConfig;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/school/*")
public class ChoiceImgServlet extends BaseServlet {

    String ctxPath = null;
    String prePath = null;
    private String path = OfficeConfig.CHOICE_IMG_PATH;
    private String NOT_FOUND = "404.png";

    @Override
    public void init(ServletConfig config) throws ServletException {
        ctxPath = config.getServletContext().getContextPath();
        if(!ctxPath.endsWith("/")){
            ctxPath += "/";
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String img = uri.substring(ctxPath.length());
        File f = null;
        if(img == null || img.contains("..")){
            f = new File(path+File.separator+NOT_FOUND);
        }else{
            f = new File(path+File.separator+img);
        }
        if(!f.isFile() || !f.exists()){
            f = new File(path+File.separator+NOT_FOUND);
        }
        if(!f.isFile() || !f.exists()){
            return;
        }
        InputStream in = new FileInputStream(f);
        byte[] buf = new byte[24];
        int len = in.read(buf);
        while (len > 0){
            resp.getOutputStream().write(buf,0,len);
            len = in.read(buf);
        }
        in.close();
    }

}
